var sw = 20,  //方块宽
    sh = 20,  //方块高
    tr = 30,  //行数
    td = 30;  //列数


var snake = null; //蛇的实例
var food = null; //食物的实例
var game = null;
// 方块构造函数  
function Square(x,y,classname){
    // 0,0 ---0,0
    // 20,0---1,0
    this.x= x*sw;
    this.y=y*sh;
    this.class=classname;

    this.viewContent = document.createElement("div");
    this.viewContent.className = this.class;
    this.parent = document.getElementById("snakewrapper");
}
Square.prototype.create = function(){
    // 创建方块DOM
    this.viewContent.style.position = "absolute";
    this.viewContent.style.width = sw + "px";
    this.viewContent.style.height = sh + "px";
    this.viewContent.style.left = this.x + "px";
    this.viewContent.style.top = this.y + "px";
    // console.log(this.parent);
    // console.log(this.viewContent);

    this.parent.appendChild(this.viewContent);
}
Square.prototype.remove = function(){
   this.parent.removeChild(this.viewContent);
}

// 蛇
function Snake(){
    this.head = null;  //存取蛇头信息
    this.tail = null; //存取蛇尾信息
    this.pos = [];//存取蛇身上每个位置
    this.dierctionNum = {
        // 存储蛇走的方向
        left:{
            x:-1,
            y:0,
            rotate:-90
        },
        right:{
            x:1,
            y:0,
            rotate:90
        },
        up:{
            x:0,
            y:-1,
            rotate:0
        },
        down:{
            x:0,
            y:1,
            rotate:180
        }
    }
}
Snake.prototype.init = function(){
    // 创建蛇头
    var snakehead = new Square(2,0,"snakehead");
    snakehead.create();
    this.head = snakehead;//存储舌头信息
    this.pos.push([2,0]);
    //存储蛇头位置

    //创建蛇身体
    var snakebody1 = new Square(1,0,"snakebody");
    snakebody1.create();
    this.pos.push([1,0]);

    var snakebody2 = new Square(0,0,"snakebody");
    snakebody2.create();
    this.tail = snakebody2;//存储蛇尾信息
    this.pos.push([0,0]);

    //链表关系
    snakehead.last = null;
    snakehead.next = snakebody1;
    snakebody1.last = snakehead;
    snakebody1.next = snakebody2;
    snakebody2.last = snakebody1;
    snakebody2.next = null;

    //给蛇添加默认方向
    this.dierction = this.dierctionNum.right;//默认向右走
}
//获取元素下一个位置，不同位置做不同的事情
Snake.prototype.getNextPos = function(){
    //蛇头下一个点
    var nextpos = [this.head.x/sw + this.dierction.x,
    this.head.y/sh + this.dierction.y]
    //下个点是自己，die
     var self = false;
     this.pos.forEach(function(value){
         if(value[0]==nextpos[0]&&value[1] ==nextpos[1]){
            self = true; 
         }
     });
     if(self){
         console.log("die");
         this.strategies.die.call(this);
         return;
     };
    

    //围墙die
    if(nextpos[0] < 0 || nextpos[0] >29||nextpos[1] < 0 ||nextpos[1] > 29){
       this.strategies.die.call(this);
       return;
    };
   

    //food 吃
    if(food && food.pos[0] == nextpos[0] && food.pos[1]==nextpos[1]){
        console.log("1111")
        this.strategies.eat.call(this);
        return;
    };

    //无 走
    this.strategies.move.call(this);

};
//处理碰撞后的事情
Snake.prototype.strategies = {
    // format决定要不要删除蛇尾
    move:function(format){
        // 创建新的身体在旧蛇头位置
        var newBody = new Square(this.head.x/sw,this.head.y/sh,"snakebody");
        this.head.remove();
        //删除旧蛇头
        newBody.create();
        //更新关系
        newBody.next = this.head.next; 
        newBody.next.last = newBody;
        newBody.last = null;

        //创建新蛇头(蛇头下一个点)
        var newhead = new Square(this.head.x/sw + this.dierction.x,this.head.y/sh + this.dierction.y,"snakehead");
        newhead.next = newBody;
        newhead.last = null;
        newBody.last = newhead;
        newhead.viewContent.style.transform="rotate("+this.dierction.rotate + "deg)";
        newhead.create();
        this.pos.splice(0,0,[this.head.x/sw + this.dierction.x,this.head.y/sh + this.dierction.y]);
        //蛇身上点位更新
        this.head = newhead;
        //蛇头信息更新
        if(!format){
            //除了吃以外执行
            this.tail.remove();
            this.tail = this.tail.last;
            this.pos.pop();
        }
    },
    eat:function(){
        this.strategies.move.call(this,true);
        createFood();
        game.score++;
    },
    die:function(){
        // console.log("die");
        game.over();
    }
}
snake = new Snake();


//创建食物
function createFood(){
    var x = null,
        y = null;
    var include = true; //循环创造食物直到食物满足条件
    while(include){
        x = Math.round(Math.random()*(td - 1));
        y=Math.round( Math.random()*(tr-1));
        
       snake.pos.forEach(function(value){
          if (value[0] != x && value[1] != y){
              include = false;
          }
       });
    }
    //生成食物
    food = new Square(x,y,"snakefood");
    food.pos = [x,y];
    var foodDOM = document.querySelector(".snakefood");
    if(foodDOM){
        foodDOM.style.left = x*sw +"px";
        foodDOM.style.top= y*sh +"px";
    }else{
        food.create();
    }
}



//创建游戏
function Game(){
    this.timer = null;
    this.score = 0;
}
Game.prototype.init = function(){
    snake.init();
    createFood();

    document.onkeydown = function(e){
        if(e.which ==37&&snake.dierction!=snake.dierctionNum.right){
            snake.dierction=snake.dierctionNum.left;
        }else if(e.which == 38 &&snake.dierction != snake.dierctionNum.down){
            snake.dierction = snake.dierctionNum.up;
        }else if(e.which == 39&&snake.dierction!=snake.dierctionNum.left){
            snake.dierction = snake.dierctionNum.right;
        }else if(e.which = 40&&snake.dierction != snake.dierctionNum.up){
            snake.dierction = snake.dierctionNum.down;
        }
    }
    this.start();
}
Game.prototype.start = function(){
    timer = setInterval(function(){
        snake.getNextPos();
    },200);
}
Game.prototype.over=function(){
    clearInterval(this.timer);
    alert("defen" + this.score);
    var snakewrap = document.getElementById("snakewrapper");
    snakewrap.innerHTML="";
    snake = new Snake();
    game = new Game();
    var startuo = document.querySelector(".start");
    startuo.style.display="block";
}

//开启游戏
game = new Game();
var startBtn = document.querySelector(".start button");
startBtn.onclick = function(){
    startBtn.parentNode.style.display="none";
    game.init();
}